package com.mzj.saas.sdk.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.mzj.saas.sdk.withdraw.vo.WxWithdrawRes;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.AlgorithmParameters;
import java.security.SecureRandom;
import java.security.Security;
import java.util.*;


/**
 * 微信工具类
 * 
 * @author JsonChen
 */
public class WechatUtils {
	private static final Logger log = LoggerFactory.getLogger(WechatUtils.class);
	
	
	private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final Random RANDOM = new SecureRandom();

	
	public static final String SUCCESS = "SUCCESS";
	public static final String FAIL = "FAIL";

	
    public static String readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            int len = 0;
            byte[] buffer = new byte[512];
            while((len = inStream.read(buffer)) != -1){
                outputStream.write(buffer, 0, len);
            }
            return new String(outputStream.toByteArray(), 0, outputStream.size(), "utf-8");
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(outputStream != null){
                outputStream.close();
            }
            if(outputStream != null){
                inStream.close();
            }
        }
        return "";
    }
	
	/**
	 * 解密微信加密数据
	 * 
	 * @param encryptedData 加密数据
	 * @param sessionkey    会话密钥
	 * @param iv            加密算法的初始向量
	 * @return
	 */
	public static JSONObject decrypt(String encryptedData, String sessionkey, String iv) {
		// 被加密的数据
		byte[] dataByte = Base64.decodeBase64(encryptedData);
		// 加密秘钥
		byte[] keyByte = Base64.decodeBase64(sessionkey);
		// 偏移量
		byte[] ivByte = Base64.decodeBase64(iv);
		try {
			// 如果密钥不足16位，那么就补足. 这个if 中的内容很重要
			int base = 16;
			if (keyByte.length % base != 0) {
				int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
				byte[] temp = new byte[groups * base];
				Arrays.fill(temp, (byte) 0);
				System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
				keyByte = temp;
			}
			// 初始化
			Security.addProvider(new BouncyCastleProvider());
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
			SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
			AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
			parameters.init(new IvParameterSpec(ivByte));
			cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
			byte[] resultByte = cipher.doFinal(dataByte);
			if (null != resultByte && resultByte.length > 0) {
				String result = new String(resultByte, "UTF-8");
				return JSONObject.parseObject(result);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 统一下单签名算法
	 * 
	 * @param params 要参与签名的数据对象
	 * @param mchKey 商户平台设置的密钥key
	 * @return 签名
	 */
	public static String getSign(SortedMap<String, Object> params, String mchKey) {
		StringBuffer sb = new StringBuffer();
		Set<Map.Entry<String, Object>> es = params.entrySet();
		Iterator<Map.Entry<String, Object>> it = es.iterator();
		while (it.hasNext()) {
			Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
			String k = (String) entry.getKey();
			Object v = entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		// 商户平台密钥key必须放在最后面
		sb.append("key=" + mchKey);
		return Md5Utils.hash(sb.toString()).toUpperCase();
	}

    /**
     * 签名算法
     * @param parameters 要参与签名的数据对象
     * @return 签名
     */
    public static String getSign(String characterEncoding,SortedMap<Object, Object> parameters, String key){
        StringBuffer sb = new StringBuffer();
        Set<Map.Entry<Object, Object>> es = parameters.entrySet();
        Iterator<Map.Entry<Object, Object>> it = es.iterator();
        while (it.hasNext()) {
            Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        /** 支付密钥必须参与加密，放在字符串最后面 */
        sb.append("key=" + key);
        String sign = Md5Utils.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }
	
	
	/**
	 * 签名验证
	 * 
	 * @param wxResultMap 微信返回的数据
	 * @param mchKey      商户平台设置的密钥key
	 * @return
	 */
	public static boolean signCheck(Map<String, Object> wxResultMap, String mchKey) {
		// 微信返回数据中的签名
		String wxSign = StrUtil.toString(wxResultMap.get("sign"));
		if (StringUtils.isBlank(wxSign)) {
			return false;
		}
		
		// 重新签名
		SortedMap<String, Object> paramMap = new TreeMap<String, Object>(wxResultMap);
		String sign = getSign(paramMap, mchKey);
		
		// 二者签名对比验证
		return wxSign.equals(sign);
	}
	
    /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
     * @param strXml
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public static Map doXMLParse(String strXml) throws JDOMException, IOException {
        strXml = strXml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

        if(null == strXml || "".equals(strXml)) {
            return null;
        }
        Map m = new HashMap();
        InputStream in = new ByteArrayInputStream(strXml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while(it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if(children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }
            m.put(k, v);
        }
        //关闭流
        in.close();

        return m;
    }

    /**
     * 获取子结点的xml
     * @param children
     * @return String
     */
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if(!children.isEmpty()) {
            Iterator it = children.iterator();
            while(it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if(!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }
        return sb.toString();
    }
	
	
	/**
	 * 将请求参数转换为xml字符串
	 * 
	 * @param params 请求参数
	 * @return
	 */
	public static String mapToXml(Map<Object, Object> params) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		for (Map.Entry<Object, Object> entry : params.entrySet()) {
			String k = (String) entry.getKey();
			Object value = entry.getValue();
			if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
				sb.append("<" + k + ">" + "<![CDATA[" + value + "]]></" + k + ">");
			} else {
				sb.append("<" + k + ">" + value + "</" + k + ">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}

	public static String mapToXmlC(Map<String, Object> params) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		for (Map.Entry<String, Object> entry : params.entrySet()) {
			String k = entry.getKey();
			Object value = entry.getValue();
			if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
				sb.append("<" + k + ">" + "<![CDATA[" + value + "]]></" + k + ">");
			} else {
				sb.append("<" + k + ">" + value + "</" + k + ">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}


    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    public static String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }
    
    public static WxWithdrawRes xmlToChangeRes(String strXML) {

		InputStream stream = null;
		try {
			WxWithdrawRes bo = new WxWithdrawRes();
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
			stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
			org.w3c.dom.Document doc = documentBuilder.parse(stream);
			doc.getDocumentElement().normalize();
			NodeList nodeList = doc.getDocumentElement().getChildNodes();
			for (int idx = 0; idx < nodeList.getLength(); ++idx) {
				Node node = nodeList.item(idx);
				if (node.getNodeType() != Node.ELEMENT_NODE) {
					continue;
				}

				org.w3c.dom.Element element = (org.w3c.dom.Element) node;
				String qName = element.getNodeName();
				if ("return_code".equals(qName)) {
					bo.setReturnCode(element.getTextContent());
				} else if ("return_msg".equals(qName)) {
					bo.setReturnMsg(element.getTextContent());
				} else if ("result_code".equals(qName)) {
					bo.setResultCode(element.getTextContent());
				} else if ("err_code".equals(qName)) {
					bo.setErrCode(element.getTextContent());
				} else if ("err_code_des".equals(qName)) {
					bo.setErrCodeDes(element.getTextContent());
				} else if ("mchid".equals(qName)) {
					bo.setMchId(element.getTextContent());
				} else if ("partner_trade_no".equals(qName)) {
					bo.setPartnerTradeNo(element.getTextContent());
				} else if ("mch_appid".equals(qName)) {
					bo.setMchAppid(element.getTextContent());
				} else if ("nonce_str".equals(qName)) {
					bo.setNonceStr(element.getTextContent());
				} else if ("payment_time".equals(qName)) {
					bo.setPaymentTime(element.getTextContent());
				} else if ("payment_no".equals(qName)) {
					bo.setPaymentNo(element.getTextContent());
				} else if ("device_info".equals(qName)) {
					bo.setDeviceInfo(element.getTextContent());
				}
			}

			return bo;
		} catch (Exception ex) {
			log.error("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(),
					strXML);
		} finally {
			try {
				stream.close();
			} catch (IOException e) {
				log.error(e.getMessage(), e);
			}
		}
		return null;

	}
	
}
